package com.ifast.asset.util;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ifast.asset.domain.*;
import com.ifast.asset.service.*;
import com.ifast.asset.service.impl.IpsegmentServiceImpl;
import com.ifast.asset.service.impl.TaskipServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;

public class CommandThread implements Runnable {
    private String tempPath = System.getProperty("java.io.tmpdir") + "/";

    String command;
    String[] commands;
    TaskrecordDO task = null;
    TaskipServiceImpl taskipServiceImpl;
    TaskrecordService taskServiceImpl;
    AssetUtil assetUtil;
    IpsegmentServiceImpl ipsegmentServiceImpl;
    AssetsService assetsService;
    LabelassetService labelassetService;
    LabelService labelService;
    SegmentService segmentService;

    public CommandThread(String command, TaskrecordDO task, TaskipServiceImpl taskipServiceImpl,
                         TaskrecordService taskServiceImpl, AssetUtil assetUtil,
                         IpsegmentServiceImpl ipsegmentServiceImpl, AssetsService assetsService,
                         LabelassetService labelassetService, LabelService labelService,SegmentService segmentService) {

        this.command = command;
        commands = composeCommand(command);
        this.task = task;
        this.taskipServiceImpl = taskipServiceImpl;
        this.taskServiceImpl = taskServiceImpl;
        this.assetUtil = assetUtil;
        this.ipsegmentServiceImpl = ipsegmentServiceImpl;
        this.assetsService = assetsService;
        this.labelassetService =  labelassetService;
        this.labelService = labelService;
        this.segmentService = segmentService;
    }


    @Override
    public void run() {
        BufferedReader reader = null;
        BufferedReader errorReader = null;
        try {
            Process p = Runtime.getRuntime().exec(commands);
            final InputStream stream = p.getInputStream();
            final InputStream errors = p.getErrorStream();
            boolean firstLine = true;
            reader = new BufferedReader(new InputStreamReader(stream));
            String line = null;
            //文件内容
            String totalLine = null;
            //System.out.println("开始输出*******************************");
            while ((line = reader.readLine()) != null) {
                //System.out.println("输出一行*******************************");
                line = escape(line);
                if (line.contains(" open")) {
                    line = "<span class=\"open\">" + line + "</span>";
                } else if (line.contains(" closed")) {
                    line = "<span class=\"closed\">" + line + "</span>";
                } else if (line.contains(" filtered")) {
                    line = "<span class=\"filtered\">" + line + "</span>";
                }
                String jump = "\n";
                if (firstLine) {
                    jump = "";
                }
                firstLine = false;
                totalLine += line;
            }
            errorReader = new BufferedReader(new InputStreamReader(errors));
            while ((line = errorReader.readLine()) != null) {

                line = escape(line);
                line = "<span class=\"closed\">" + line + "</span>";
                String jump = "\n";
                if (firstLine) {
                    jump = "";
                }
                //cmd.getOutput().setText(cmd.getOutput().getText() + jump + "<i>" + line + "</i>");
                firstLine = false;
                totalLine += line;
            }
            System.out.println("打印输出日志：" + totalLine);
            //将日志保存  更新task  中log属性
            TaskrecordDO taskNew = taskServiceImpl.selectById(task.getId());
            taskNew.setStatus(1);
            taskServiceImpl.updateById(taskNew);
            //从返回日志中解析   参数
            getMesFromText(totalLine, task.getId());


        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (reader != null) {
                try {
                    reader.close();
                    System.out.println("正常输出断开");
                } catch (IOException e) {
                }
            }
            if (errorReader != null) {
                try {
                    errorReader.close();
                    System.out.println("错误输出断开");
                } catch (IOException e) {

                }
            }
        }
    }

    private String escape(String str) {
        String line = str;
        line = line.replace("&", "&amp;");
        line = line.replace("\"", "&quot;");
        line = line.replace("<", "&lt;");
        line = line.replace(">", "&gt;");
        return line;
    }

    private String[] composeCommand(String command) {

        String filename = "nmap-scan_" + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
                .format(new Date()) + ".xml";
        tempPath = tempPath + filename;
        List<String> commandList = new ArrayList<String>();
        //nmap指令
        commandList.add("nmap");
        if (!"".equals(command)) {
            //不是第一次进入  此函数
            //commandList.add("-sS");
            //commandList.add("-T4");
            //commandList.add("-A");
            commandList.add("-sU");
            commandList.add("-sT");
            commandList.add("-F");
            commandList.add("-O");
            //commandList.add("-sC");
            //commandList.add("-oA");
            //获取路径
            //commandList.add(UUID.randomUUID().toString()); //"/opt/log/"+UUID.randomUUID().toString()
            commandList.add(command);
        }
        commandList.addAll(Arrays.asList(new String[]{"-oX", getTempPath(), "--webxml"}));

        return commandList.toArray(new String[]{});

    }

    public String getTempPath() {
        return tempPath;
    }

    //在nmap返回的结果中   解析数据
    public void getMesFromText(String text, int taskId) {

        List<TaskipDO> taskIps = new ArrayList<>();

        //解析text字符串
        String[] ipMsgs = text.split("Nmap scan report for ");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        for (int i = 1; i < ipMsgs.length; i++) {

            TaskipDO taskIp = new TaskipDO();
            List<Map<String, Object>> ipMsgList = new ArrayList<>();
            String textMsg = ipMsgs[i];
            //获取ip
            String ip = StringUtils.substringBefore(textMsg, "Host is up").replace(" ", "");
            System.out.println(ip);
            //ip = ip.replace("localhost(", "").replace(")", "").replace("(", "");
            //taskIp.setIp(ip);
            ip = ip.replace("localhost(", "");
            if (ip.contains("(")) {

                String[] ips = ip.split("\\(");
                taskIp.setIp(ips[1].replace(")", ""));
                taskIp.setDomain(ips[0]);
            } else {
                taskIp.setIp(ip);
            }
            List<Map<String, Object>> portList = new ArrayList<>();
            //解析字符串中的端口与服务
            while (textMsg.contains("</span>")) {

                Map<String, Object> map = new HashMap<>();
                String ifHaveWarring = StringUtils.substringBefore(StringUtils.substringAfter(textMsg, "<span class"), "</span>");
                if (ifHaveWarring.contains("Warning") || ifHaveWarring.contains("WARNING")) {
                    //去除MAC Address 后面存在warring的情况
                    break;
                }
                try {
                    if (ifHaveWarring.contains("Not shown")) {

                        //去除类似<span class="filtered">Not shown: 998 filtered ports</span>的信息
                        continue;
                    }
                    String portString = StringUtils.substringBefore(StringUtils.substringAfter(textMsg, "<span class"), "</span>");
                    String[] stringArrays = StringUtils.substringAfter(portString, ">").split("\\s+");
                    //System.out.println(portString);
                    try {
                        String port = stringArrays[0].split("/")[0];
                        String type = stringArrays[0].split("/")[1];
                        //System.out.println(port+type);
                        if ("".equals(port) || "".equals(type)) {
                            continue;
                        }
                        map.put("port", port);
                        map.put("type", type);
                    } catch (Exception e) {
                    }
                    try {
                        String status = stringArrays[1];
                        map.put("status", status);
                        //System.out.println(status);
                    } catch (Exception e) {

                    }
                    try {
                        String service = stringArrays[2];
                        map.put("service", service);
                        //System.out.println(service);
                    } catch (Exception e) {
                    }
                    try {
                        String version = stringArrays[3];
                        map.put("version", version);
                        //System.out.println(version);
                    } catch (Exception e) {
                    }
                } catch (Exception e) {

                    e.printStackTrace();
                } finally {
                    //去除解析完成字符串信息
                    textMsg = StringUtils.substringAfter(textMsg, "</span>");
                }
                ipMsgList.add(map);
            }
            //mac地址
            if (textMsg.contains("MAC Address")) {

                //解析mac
                String macAddress = StringUtils.substringBefore(StringUtils.substringAfter(textMsg, "MAC Address:"), "(");
                textMsg = StringUtils.substringAfter(textMsg, macAddress);
                //解析厂商
                String vendor = StringUtils.substringBefore(textMsg, ")").replace("(", "").replace(")", "");
                textMsg = StringUtils.substringAfter(textMsg, ")");
                //System.out.println("MAC Address:"+macAddress+vendor);
                taskIp.setMac(macAddress);
                taskIp.setVendor(vendor);
            }
            //解析设备类型Device type
            if (textMsg.contains("Device type")) {

                //解析设备类型
                String deviceType = StringUtils.substringBefore(StringUtils.substringAfter(textMsg, "Device type: "), " ");
                //System.out.println("deviceType:"+deviceType);
                taskIp.setDevicetype(deviceType);
            }
            //解析操作系统 Running
            if (textMsg.contains("Running")) {
                String os = "";
                //解析设备类型
                if (!textMsg.contains("JUST GUESSING")) {
                    os = StringUtils.substringBefore(StringUtils.substringAfter(textMsg, "Running: "), " ");
                } else {
                    os = StringUtils.substringBefore(StringUtils.substringAfter(textMsg, "Running (JUST GUESSING): "), " ");
                }
                //System.out.println("os:"+os);
                taskIp.setOs(os);
            }
            taskIp.setPort(JSON.toJSONString(ipMsgList));
            taskIp.setPortnum(ipMsgList.size());
            taskIp.setTaskId(taskId);
            taskIp.setTime(time);
            taskIps.add(taskIp);
        }

        //查询 所有的nmap检测目标
        List<String> list = new ArrayList<>();
        if (command.contains("/")){
            String[] str = command.split("/");
            list = IpUtil.getLocalAreaIpList(str[0],IpUtil.intToMask(Integer.valueOf(str[1])),true,true);
        }


        //将nmap检测出来有结果的 taskIps保存
        for (int i = 0; i < taskIps.size(); i++) {

            TaskipDO taskipDO = taskIps.get(i);
            taskipServiceImpl.insert(taskipDO);
            setSegment(taskipDO.getIp(),"1",time);
            if (list.size()>0){
                list.remove(taskipDO.getIp());
            }
        }
        List<SegmentDO>segmentDOS = segmentService.selectList(null);
        for (int i = 0 ; i < segmentDOS.size() ; i++){

            if (list.contains(segmentDOS.get(i).getIp())){

                setSegment(list.get(i),"0",time);

            }
        }

        getChange( taskIps);
    }

    //增加设备运行状态
    public void setSegment(String ip,String status,String time){
        Assets asset = null;
        //判断资产列表中是否含有此ip  如果不含  则添加
        Wrapper assetWrapper = new EntityWrapper<>();
        assetWrapper.eq("ip", ip);
        asset = assetsService.selectOne(assetWrapper);
        if (asset == null) {
            //添加
            asset = new Assets();
            asset.setIp(ip.replace("\\n", ""));
            asset.setLabel("默认资产");
            asset.setSource("1");
            asset.setTime(time);
            assetsService.insert(asset);
        }

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("ip",ip);
        SegmentDO segmentDO = segmentService.selectOne(wrapper);
        if (segmentDO==null){
            segmentDO = new SegmentDO();
            segmentDO.setIp(ip);
            segmentDO.setStatus(status);
            segmentDO.setTime(time);
            segmentService.insert(segmentDO);
        }else {
            segmentDO.setStatus(status);
            segmentDO.setTime(time);
            segmentService.updateById(segmentDO);
        }
    }

    public static List<String> executeLinuxCmd(String cmd) {
        //System.out.println("got cmd job : " + cmd);
        Runtime run = Runtime.getRuntime();
        try {
//            Process process = run.exec(cmd);
            Process process = run.exec(new String[]{"/bin/sh", "-c", cmd});
            InputStream in = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(in));
            List<String> list = new ArrayList<String>();
            String result = null;
            while ((result = bs.readLine()) != null) {
                System.out.println("job result [" + result + "]");
                list.add(result);
            }
            in.close();
            // process.waitFor();
            process.destroy();
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //资产变更
    public void getChange(List<TaskipDO> lists) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < lists.size(); i++) {

            if (lists.get(i).getIp()==null||"".equals(lists.get(i).getIp())){

                //ip不能为空   为空则跳过
                continue;
            }
            //判断当前添加资产是否属于已添加网段
            List<IpsegmentDO> list = ipsegmentServiceImpl.selectList(null);

            if (list.size() == 0) {
                IpsegmentDO ipsegmentDO = new IpsegmentDO();
                String[] ip = (lists.get(i).getIp()).split("\\.");
                ipsegmentDO.setIp(ip[0] + "." + ip[1] + "." + ip[2] + ".0/24");
                ipsegmentServiceImpl.insert(ipsegmentDO);

            } else {
                for (int j = 0; j < list.size(); j++) {

                    boolean isContain = IpUtil.getIsCrossIp(list.get(j).getIp(), lists.get(i).getIp());
                    if (isContain) {
                        //包含
                        break;
                    } else {
                        if (j == list.size() - 1) {
                            //不包含 则添加
                            IpsegmentDO ipsegmentDO = new IpsegmentDO();
                            String[] ip = (lists.get(i).getIp()).split("\\.");
                            ipsegmentDO.setIp(ip[0] + "." + ip[1] + "." + ip[2] + ".0/24");

                            //判断是否已经存在此ip段
                            Wrapper wrapper = new EntityWrapper();
                            wrapper.eq("ip", ipsegmentDO.getIp());
                            List<IpsegmentDO> ipsegmentDOS = ipsegmentServiceImpl.selectList(wrapper);
                            if (ipsegmentDOS.size() == 0) {
                                ipsegmentServiceImpl.insert(ipsegmentDO);
                            }
                        }
                    }
                }
            }

            lists.get(i).setIp(lists.get(i).getIp().replaceAll("[^\\d.]", ""));
            TaskipDO newTaskipDO = lists.get(i);

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {

                    assetUtil.openAndDown(newTaskipDO, task.getId());
                }
            });
            thread.start();

            //lists.get(i).setTaskId( taskrecordDO.getId());
            Date time = new Date();
            lists.get(i).setTime(simpleDateFormat.format(time));
            //存储检测记录
            //taskipServiceImpl.insert(lists.get(i));
            //存储资产
            Assets asset = null;
            //判断资产列表中是否含有此ip  如果不含  则添加
            Wrapper assetWrapper = new EntityWrapper<>();
            assetWrapper.eq("ip", lists.get(i).getIp());
            asset = assetsService.selectOne(assetWrapper);
            if (asset==null){
                return;
            }
            //存储资产标签
            List<String> jsons = JsonUtil.parseService(lists.get(i).getPort());
            LabelDO label = null;
            //将旧标签删除   然后把资产与新标签绑定
            Wrapper labelLassetWrapper = new EntityWrapper();
            labelLassetWrapper.eq("assetId", asset.getId());
            labelassetService.delete(labelLassetWrapper);
            //判断当前是否含有标签
            for (int j = 0; j < jsons.size(); j++) {

                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("name", jsons.get(j));
                label = labelService.selectOne(wrapper);
                if (label != null) {
                    //征明此时已经存在此标签

                } else {
                    label = new LabelDO();
                    label.setName(jsons.get(j));
                    label.setFlag(1);
                    labelService.insert(label);
                }

                LabelassetDO labelassetDO = new LabelassetDO();
                labelassetDO.setAssetId(asset.getId());
                labelassetDO.setLabelId(label.getId());
                labelassetService.insert(labelassetDO);
            }

            //添加开机记录
           /* boolean falg = IpUtil.ping(asset.getIp());
            if (falg) {
                //ping的通说明设备在线
                SegmentDO segment = new SegmentDO();
                segment.setIp(asset.getIp());
                //判断是否存在 次ip的记录
                Wrapper w = new EntityWrapper(segment);
                if (segmentService.selectOne(w) == null) {

                    segment.setStatus("1");
                    segment.setTime(simpleDateFormat.format(new Date()));
                    segmentService.insert(segment);
                } else {
                    segment.setId(segmentService.selectOne(w).getId());
                    segment.setStatus("1");
                    segment.setTime(simpleDateFormat.format(new Date()));
                    segmentService.updateAllColumnById(segment);
                }

            } else {
                //ping不通说明设备不在线
                SegmentDO segment = new SegmentDO();
                segment.setIp(asset.getIp());
                Wrapper w = new EntityWrapper(segment);
                if (segmentService.selectOne(w) == null) {

                    segment.setStatus("0");
                    segment.setTime(simpleDateFormat.format(new Date()));
                    segmentService.insert(segment);
                } else {
                    segment.setId(segmentService.selectOne(w).getId());
                    segment.setStatus("0");
                    segment.setTime(simpleDateFormat.format(new Date()));
                    segmentService.updateAllColumnById(segment);
                }
            }*/
        }
    }
}
